/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ro.pub.cs.dfsa.client.connection;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author Narcis
 */
public class TCPClientConnection extends AbstractClientConnection {
    
    private Socket clientSocket;
	private ObjectOutputStream oos;
    private ObjectInputStream ois;
    
    public TCPClientConnection() {
    }
    
    public TCPClientConnection(Socket clientSocket) throws IOException {
    	this.clientSocket = clientSocket;
    	oos = new ObjectOutputStream(clientSocket.getOutputStream());
        ois = new ObjectInputStream(clientSocket.getInputStream());
    }
    
    @Override
    public void createConnection() throws IOException {
        clientSocket = new Socket(serverAddress,serverPort);
        oos = new ObjectOutputStream(clientSocket.getOutputStream());
        ois = new ObjectInputStream(clientSocket.getInputStream());
    }
    
    @Override
    public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException {
        return (T) ois.readObject();
    }

    @Override
    public void writeObject(Object o) throws IOException {
        oos.writeObject(o);
    }
    
    @Override
    public boolean isClosed() {
        return clientSocket == null;
    }
    
    @Override
    public void close() throws IOException {
        ois.close();
        oos.close();
        clientSocket.close();
        clientSocket = null;
    }
}
